package com.avic.modules.backup4Dameng.remote;

import com.avic.modules.backup4Dameng.DmpBackup;
import com.avic.utils.DateUtils;
import com.jcraft.jsch.*;
import org.apache.commons.compress.utils.IOUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class SfCopyRemote {


    public static void main(String[] args) {

        String addr = "192.168.110.253";
        String logName = DateUtils.dateTimeNow().concat("dexp.log");
        String dmpName = DateUtils.dateTimeNow().concat(".dmp");
        String dexpPath = "D:\\\\software\\\\sql\\\\dmdbms\\\\bin\\\\dexp.exe";
        String dexpURL = "SYSDBA/Admin123456@LOCALHOST:5236";
        String exportDirectory = "C:\\\\Users\\\\Administrator\\\\Desktop";
        String winAdmin = "Administrator";
        String winAdminPass =  "Admin123";
        String dexpCmd = String.format("%s %s DIRECTORY=%s FILE=%s SCHEMAS=\"SCADA\" TABLESPACE=N DROP=N LOG=%S  LOG_WRITE=N", dexpPath, dexpURL, exportDirectory, dmpName, logName);
        System.out.println(dexpCmd);
        exportDmp(addr,dexpPath,dexpURL,exportDirectory, winAdmin, winAdminPass);

    }

    public static Session executeCommand(String host, String username, String password, String command,String exportDir) throws JSchException, IOException {
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        JSch jsch = new JSch();
        Session session = jsch.getSession(username, host, 22);
        session.setPassword(password);
        session.setConfig(config);
        session.connect();
        System.out.println("Connected");
        Channel channel = session.openChannel("exec");

        ((ChannelExec) channel).setCommand(command);
        channel.setInputStream(null);
        ((ChannelExec) channel).setErrStream(System.err);
        InputStream in = channel.getInputStream();
        channel.connect();
        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0) break;
                System.out.print(new String(tmp, 0, i, "GBK"));
            }
            if (channel.isClosed()) {
                System.out.println("exit-status: " + channel.getExitStatus());
                break;
            }
            try {
                Thread.sleep(3000);
            } catch (Exception ignored) {
            }
        }
        channel.disconnect();
        return session;
    }

    public static void download(Session session, String source, String dest,String exportDir) {
        int port = 22;
        Channel channel = null;
        try {
            session.setTimeout(20 * 1000);
            channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp channelSftp = (ChannelSftp) channel;
            System.out.println("Starting File download");
            channelSftp.cd(exportDir);
            InputStream is = channelSftp.get("C:\\\\Users\\\\Administrator\\\\Desktop\\\\20220701143005.dmp");
            File file = new File(dest);
            if(!file.exists()){
                file.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(file);
            IOUtils.copy(is, fos);
            System.out.format("scp execute DONE ，dest:%s",dest);
            is.close();
            fos.close();
            fos.flush();
        } catch (JSchException | SftpException | IOException exception) {
            exception.printStackTrace();
        } finally {
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }

    public static String exportDmp(String addr, String remoteDexpPath, String dexpURL, String remoteDexpDirectory, String winAdmin, String winAdminPass) {

        String logName = DateUtils.dateTimeNow().concat("dexp.log");
        String dmpName = DateUtils.dateTimeNow().concat(DmpBackup.DMP_EXTENSION);
        String dexpCmd = String.format("%s %s DIRECTORY=%s FILE=%s SCHEMAS=\"SCADA\" TABLESPACE=N DROP=N LOG=%S  LOG_WRITE=N", remoteDexpPath, dexpURL, remoteDexpDirectory, dmpName, logName);
        String dmpFilePath = remoteDexpDirectory.concat("\\\\" + dmpName);
        FileOutputStream fos = null;
        try {
            Session session = executeCommand(addr,winAdmin,winAdminPass,dexpCmd,remoteDexpDirectory);
            String dest = DmpBackup.DMP_EXTERNAL_DIR.concat(dmpName);
            download(session, dmpName,dest,remoteDexpDirectory);
        } catch (Exception ex) {
            throw new RuntimeException("Dexp sch command exec wrong Caused by: " + ex.getMessage());
        }
        return dmpName;
    }

}
